<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
			label-width="68px">
			<el-form-item label="学校">
				<el-select v-model="queryParams.schoolid" placeholder="请选择学校" clearable
					@change="changeSchool">
					<el-option v-for="item in schools" :label="item.schoolname" :key="item.schoolid"
						:value="item.schoolid">
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="评论者id" prop="userid">
				<el-input v-model="queryParams.userid" placeholder="请输入评论者id" clearable
					@keyup.enter.native="handleQuery" />
			</el-form-item>
			<el-form-item label="帖子id" prop="contentid">
				<el-input v-model="queryParams.contentid" placeholder="请输入帖子id" clearable
					@keyup.enter.native="handleQuery" />
			</el-form-item>
			<!-- 			<el-form-item label="子评论所在主评论的id" prop="replycommentid">
				<el-input v-model="queryParams.replycommentid" placeholder="请输入子评论所在主评论的id" clearable
					@keyup.enter.native="handleQuery" />
			</el-form-item> -->
			<el-form-item label="评论内容" prop="commenttext">
				<el-input v-model="queryParams.commenttext" placeholder="请输入评论内容" clearable
					@keyup.enter.native="handleQuery" />
			</el-form-item>
			<!-- <el-form-item label="评论状态" prop="commentstate">
				<el-input v-model="queryParams.commentstate" placeholder="" clearable
					@keyup.enter.native="handleQuery" />
			</el-form-item> -->
			<el-form-item label="评论状态" prop="commentstate">
				<el-select v-model="queryParams.commentstate" placeholder="请选择评论状态" clearable>
					<el-option v-for="dict in dict.type.bbs_comment_state" :key="dict.value"
						:label="dict.label" :value="dict.value">
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
			<!-- 			<el-col :span="1.5">
				<el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single"
					@click="handleUpdate">修改</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
					@click="handleDelete">删除</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
			</el-col> -->
			<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
		</el-row>

		<el-table v-loading="loading" :data="commentList" @selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55" align="center" />
			<el-table-column label="评论人员昵称" align="center">
				<template slot-scope="scope">
					<el-button size="mini" type="text" @click="toUserPage(scope.row)">
						{{scope.row.nickname}}
					</el-button>
				</template>
			</el-table-column>
			<!-- 			<el-table-column label="子评论所在主评论的id" align="center" prop="replycommentid" />
			<el-table-column label="是否是子评论对子评论的评论1：是；0：否" align="center" prop="isreply" /> -->
			<!-- <el-table-column label="子评论回复的子评论对象名称" align="center" prop="replynickname" /> -->
			<el-table-column label="评论内容" align="center" prop="commenttext" />
			<el-table-column label="评论图片" align="center" prop="commenturl">
				<template slot-scope="scope" v-if="scope.row.commenturl">
					<image-preview :src="scope.row.commenturl" :width="50" :height="50" />
				</template>
			</el-table-column>
			<el-table-column label="评论类型" align="center" prop="ismain">
				<template slot-scope="scope">
					<span v-if="scope.row.ismain === 1" class="normal-tag">主评论</span>
					<span v-else-if="scope.row.ismain === 0" class="abnormal-tag">子评论</span>
				</template>
			</el-table-column>
			<el-table-column label="回复对象" align="center" prop="replynickname" />
			<el-table-column label="点赞数" align="center" prop="upnum" />
			<el-table-column label="举报数量" align="center" prop="informnum" />
			<el-table-column label="评论状态" align="center" prop="commentstate">
				<template slot-scope="scope">
					<dict-tag :options="dict.type.bbs_comment_state" :value="scope.row.commentstate" />
				</template>
			</el-table-column>
			<el-table-column label="创建时间" align="center" prop="createtime" width="180">
				<template slot-scope="scope">
					<span>{{ parseTime(scope.row.createtime) }}</span>
				</template>
			</el-table-column>
			<el-table-column label="跳转原帖" align="center" class-name="small-padding fixed-width">
				<template slot-scope="scope">
					<el-button size="mini" type="text" icon="el-icon-edit" @click="toContentPage(scope.row)">查看
					</el-button>
				</template>
			</el-table-column>
			<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
				<template slot-scope="scope">
					<el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改
					</el-button>
				</template>
			</el-table-column>
		</el-table>

		<pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
			@pagination="getList" />

		<!-- 添加或修改评论对话框 -->
		<el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
			<el-form ref="form" :model="form" :rules="rules" label-width="80px">
				<!-- <el-form-item label="评论者id" prop="userid">
					<el-input v-model="form.userid" placeholder="请输入评论者id" />
				</el-form-item>
				<el-form-item label="帖子id" prop="contentid">
					<el-input v-model="form.contentid" placeholder="请输入帖子id" />
				</el-form-item>
				<el-form-item label="子评论所在主评论的id" prop="replycommentid">
					<el-input v-model="form.replycommentid" placeholder="请输入子评论所在主评论的id" />
				</el-form-item>
				<el-form-item label="是否是子评论对子评论的评论1：是；0：否" prop="isreply">
					<el-input v-model="form.isreply" placeholder="请输入是否是子评论对子评论的评论1：是；0：否" />
				</el-form-item>
				<el-form-item label="子评论回复的子评论对象名称" prop="replynickname">
					<el-input v-model="form.replynickname" placeholder="请输入子评论回复的子评论对象名称" />
				</el-form-item>
				<el-form-item label="1：主评论；0：评论的评论" prop="ismain">
					<el-input v-model="form.ismain" placeholder="请输入1：主评论；0：评论的评论" />
				</el-form-item>
				<el-form-item label="评论内容" prop="commenttext">
					<el-input v-model="form.commenttext" placeholder="请输入评论内容" />
				</el-form-item>
				<el-form-item label="评论的图片，以逗号分割的形式存储" prop="commenturl">
					<el-input v-model="form.commenturl" type="textarea" placeholder="请输入内容" />
				</el-form-item>
				<el-form-item label="点赞数" prop="upnum">
					<el-input v-model="form.upnum" placeholder="请输入点赞数" />
				</el-form-item>
				<el-form-item label="“踩”数" prop="downnum">
					<el-input v-model="form.downnum" placeholder="请输入“踩”数" />
				</el-form-item>
				<el-form-item label="举报数量" prop="informnum">
					<el-input v-model="form.informnum" placeholder="请输入举报数量" />
				</el-form-item> -->
				<el-form-item label="评论状态" prop="commentstate">
					<el-select v-model="form.commentstate" placeholder="请选择状态">
						<el-option v-for="dict in dict.type.bbs_comment_state" :key="dict.value" :label="dict.label"
							:value="dict.value">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="创建时间" prop="createtime">
					<el-date-picker clearable v-model="form.createtime" type="datetime" placeholder="请选择创建时间">
					</el-date-picker>
				</el-form-item>
				<el-form-item v-if="commentOldForm.commentstate!=form.commentstate" label="操作记录备注" prop="note">
					<el-input v-model="operatinForm.note" placeholder="请输入操作记录备注" />
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import {
		listComment,
		getComment,
		delComment,
		addComment,
		updateComment,
		listCommentBySchool
	} from "@/api/bbs_comment/comment";
	import {
		addBbs_operation_record,
	} from "@/api/bbs_operation_record/bbs_operation_record";
	import {
		getAllSchools,
		listBbs_user,
		getBbs_user
	} from "@/api/bbs_user/bbs_user";
	import {
		listPlateCate,
		listPlateTree
	} from "@/api/bbs_plate/plate.js";
	import schoolInfoList from '../../utils/schoolInfo.js'
	export default {
		name: "Comment",
		dicts: ['bbs_comment_state', 'bbs_true_or_false'],
		data() {
			return {
				// 遮罩层
				loading: true,
				// 选中数组
				ids: [],
				// 非单个禁用
				single: true,
				// 非多个禁用
				multiple: true,
				// 显示搜索条件
				showSearch: true,
				// 总条数
				total: 0,
				// 评论表格数据
				commentList: [],
				// 弹出层标题
				title: "",
				// 是否显示弹出层
				open: false,
				// 查询参数
				queryParams: {
					pageNum: 1,
					pageSize: 10,
					userid: null,
					contentid: null,
					replycommentid: null,
					isreply: null,
					replynickname: null,
					ismain: null,
					commenttext: null,
					commenturl: null,
					upnum: null,
					downnum: null,
					informnum: null,
					commentstate: null,
					createtime: null,
					updatetime: null,
					schoolid:null,
					orderByColumn: 'createtime'
				},
				// 表单参数
				form: {},
				// 表单校验
				rules: {},
				//操作记录有关
				commentOldForm: {},
				operatinForm: {
					// id: null,
					schoolId: null,
					recordState: 1,
					operator: null,
					targetKind: null,
					targetId: null,
					changeInfo: null,
					note: null,
				},
				//学校列表
				currentschools: [],
				schools: [],
			};
		},
		created() {
			this.getSchools();
			// this.getList();
			if (!this.$route.query.userId && !this.$route.query.contentId) {
				// console.log('触发')
				// this.getContentVoList();
				this.getList();
			}
		},
		activated: function() {
			if (this.$route.query.userId) {
				console.log('参数', this.$route.query.userId)
				this.queryParams.userid = this.$route.query.userId
				this.getList();
				// this.queryParams.userid = null
			}
			if (!this.$route.query.userId && !this.$route.query.contentId) {
				// console.log('无参数')
				this.getList();
			}
		
		},
		beforeRouteLeave(to,from,next){
			console.log('离开页面时调用的方法');
			// 清空条件
			this.queryParams.userid = null;
			// 清除当前页面的路由参数
			// const data =this.$route
			// console.log('当前路由',data)
			if (this.$route.query.userId) {
				delete this.$route.query.userId
			}
			next();
		},
		methods: {
			/** 查询评论列表 */
			async getList() {
				this.loading = true;
				this.queryParams.schoolid= this.$store.state.user.currentSchool.schoolid
				// const response = await listComment(this.queryParams);
				const response = await listCommentBySchool(this.queryParams);
				if (response.code == 200) {
					console.log(response);
					for (var i = 0; i < response.rows.length; i++) {
						const userResponse = await getBbs_user(response.rows[i].userid);
						// console.log('用户信息', userResponse, i);
						response.rows[i].nickname = userResponse.data.nickname;
					}
					this.commentList = response.rows;
					this.total = response.total;
					this.loading = false;
				}
				// listComment(this.queryParams).then(response => {
				// 	console.log(response);
				// 	this.commentList = response.rows;
				// 	for (var i = 0; i < response.rows.length; i++) {
				// 		const userResponse = await getBbs_user(response.rows[i].operator);
				// 		console.log('用户信息', userResponse, i);
				// 		response.rows[i].operatorName = userResponse.data.nickname;
				// 	}
				// 	this.total = response.total;
				// 	this.loading = false;
				// });
			},
			// 取消按钮
			cancel() {
				this.open = false;
				this.reset();
			},
			// 表单重置
			reset() {
				this.form = {
					commentid: null,
					userid: null,
					contentid: null,
					replycommentid: null,
					isreply: null,
					replynickname: null,
					ismain: null,
					commenttext: null,
					commenturl: null,
					upnum: null,
					downnum: null,
					informnum: null,
					commentstate: null,
					createtime: null,
					updatetime: null
				};
				this.resetForm("form");
			},
			/** 搜索按钮操作 */
			handleQuery() {
				this.queryParams.pageNum = 1;
				this.getList();
			},
			/** 重置按钮操作 */
			resetQuery() {
				this.resetForm("queryForm");
				this.handleQuery();
			},
			// 多选框选中数据
			handleSelectionChange(selection) {
				this.ids = selection.map(item => item.commentid)
				this.single = selection.length !== 1
				this.multiple = !selection.length
			},
			/** 新增按钮操作 */
			handleAdd() {
				this.reset();
				this.open = true;
				this.title = "添加评论";
			},
			/** 修改按钮操作 */
			handleUpdate(row) {
				this.reset();
				const commentid = row.commentid || this.ids
				getComment(commentid).then(response => {
					this.form = response.data;
					this.form.commentstate = row.commentstate.toString();
					//将此时的form复制一份，存起来
					this.commentOldForm = JSON.parse(JSON.stringify(this.form))
					this.operatinForm.note = null;
					this.open = true;
					this.title = "修改评论";
				});
			},
			/** 提交按钮 */
			submitForm() {
				this.$refs["form"].validate(valid => {
					if (valid) {
						if (this.form.commentid != null) {
							updateComment(this.form).then(response => {
								this.$modal.msgSuccess("修改成功");
								this.createOperationRecord(3,this.commentOldForm,this.form)
								this.open = false;
								this.getList();
							});
						} else {
							addComment(this.form).then(response => {
								this.$modal.msgSuccess("新增成功");
								this.open = false;
								this.getList();
							});
						}
					}
				});
			},
			//创建操作记录
			createOperationRecord(targetKind,oldInfo,newInfo) {
				console.log("触发")
				//构建操作记录
				this.operatinForm.schoolId = this.$store.state.user.currentSchool.schoolid;
				this.operatinForm.operator = this.$store.state.user.name;
				this.operatinForm.targetKind = targetKind;
				//操作对象为评论
				if (targetKind==3) {
					this.operatinForm.targetId = newInfo.commentid;
				}
				this.operatinForm.changeInfo = {
					data: {
						oldForm: {},
						newForm: {}
					}
				};
				//获取变更了属性值
				let haveChange =0;
				for (let key in newInfo) {
					let value = newInfo[key];
					// 在这里对属性进行处理
					// console.log(key + ': ' + typeof newInfo[key]);
					if (typeof newInfo[key] !='object' &&newInfo[key]!=oldInfo[key]) {
						haveChange=1
						this.operatinForm.changeInfo.data.oldForm[key] =oldInfo[key]
						this.operatinForm.changeInfo.data.newForm[key] =newInfo[key]
					}
					if (targetKind==3 && key == 'contentid') {
						this.operatinForm.changeInfo.data.oldForm[key] =oldInfo[key]
						this.operatinForm.changeInfo.data.newForm[key] =newInfo[key]
					}
				}
				if (haveChange==1) {
					this.operatinForm.changeInfo = JSON.stringify(this.operatinForm.changeInfo)
					console.log(this.operatinForm)
					addBbs_operation_record(this.operatinForm).then(response => {
						this.$modal.msgSuccess("操作记录新增成功");
					});
				}
			},
			//跳转用户界面
			toUserPage(data) {
				console.log('触发', data)
				this.contentVisible = false
				this.$router.push({
					path: '/bbs_user_school/bbs_user',
					query: {
						id: data.userid
					}
				})
			},
			//跳转帖子界面
			toContentPage(data) {
				// console.log('触发', data)
				this.$router.push({
					path: '/bbs_user_school/content',
					query: {
						contentId: data.contentid
					}
				})
			},
			changeSchool(value){
				console.log("改变", value)
				this.queryParams.schoolid = value
				this.currentschools = [schoolInfoList.selectOneSchoolInfo(value)]
				this.$store.commit('SET_currentSchool', schoolInfoList.selectOneSchoolInfo(value))
				this.queryParams.pageNum = 1;
				this.getList()
				
			},
			getSchools() {
				getAllSchools().then((response) => {
					this.schools = response.data;
					this.schools = this.schools.map((x) => {
						x["name"] = x["schoolname"];
						return x;
					});
				});
			},
			/** 删除按钮操作 */
			handleDelete(row) {
				const commentids = row.commentid || this.ids;
				this.$modal.confirm('是否确认删除评论编号为"' + commentids + '"的数据项？').then(function() {
					return delComment(commentids);
				}).then(() => {
					this.getList();
					this.$modal.msgSuccess("删除成功");
				}).catch(() => {});
			},
			/** 导出按钮操作 */
			handleExport() {
				this.download('bbsAdmin/comment/export', {
					...this.queryParams
				}, `comment_${new Date().getTime()}.xlsx`)
			}
		}
	};
</script>
